package my.mark.mybaibaoxiang.juc.biji06;

import java.util.concurrent.Semaphore;

/**
 * @author wxming.
 * @description :可用于流量控制，限制最大的并发访问数。控制访问特定资源的线程数目
 */
public class SemaphoreSample {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);//信号量2，同时只能有2个线程执行。
        for (int i = 0; i < 5; i++) {
            new Thread(new Task(semaphore, "yangguo+" + i)).start();
        }
    }

    static class Task extends Thread {
        Semaphore semaphore;

        public Task(Semaphore semaphore, String tname) {
            this.semaphore = semaphore;
            this.setName(tname);
        }

        public void run() {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + ":aquire() at time:" + System.currentTimeMillis());
                Thread.sleep(5000);
                semaphore.release();
                System.out.println(Thread.currentThread().getName() + ":release() at time:" + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
